//
//  WBMainViewController.swift
//  个人微博
//
//  Created by 任聪聪 on 2017/5/16.
//  Copyright © 2017年 任孜聪. All rights reserved.
//
// 主控制器
import UIKit
import SVProgressHUD
class WBMainViewController: UITabBarController {
    //定义定时器
    fileprivate var timer:Timer?
    override func viewDidLoad() {
        super.viewDidLoad()
        getChildControllers()
        setUpComposeButton()
        setUpTimer()
        //是否显示新特性界面
        isShowNewFeature()
        //UITabBarController设置代理
        delegate = self
//        //调用还未读取的新浪微博数量
//        WBNetWorkManager.shared.unReadCount { (Count) in
//            print("还有\(Count)条微博未读")
//        }
        //接收消息注册消息通知、
        NotificationCenter.default.addObserver(self, selector: #selector(userLogin(n:)), name: NSNotification.Name(rawValue: WBUserShouldLoginNotification), object: nil)
        //注册登录成功通知
        NotificationCenter.default.addObserver(self, selector: #selector(userLoginSucess), name: NSNotification.Name(rawValue: WBUserLoginSucessNotification), object: nil)
    }
    //用户登录成功
    @objc func userLoginSucess(n:NotificationCenter) {
        print("登录成功\(n)")
        //view视图调用getter方法，view=nil会调用viewDidLoad方法重新设置界面
        view = nil
        //再次注销监听，防止通知被注册两次,通知每发送一次，只能注册完成一次。
        NotificationCenter.default.removeObserver(self)
    }
    //用户登录事件
    @objc fileprivate func userLogin(n:NSNotification) {
        print("用户登录"+"\(n)")
        var when = DispatchTime.now()
        if n.object != nil {
            //设置提示框渐变样式
            SVProgressHUD.setDefaultMaskType(.gradient)
            SVProgressHUD.showInfo(withStatus: "用户信息已经过期，请重新登录。")
            when = when + 2
        }
        DispatchQueue.main.asyncAfter(deadline: when) {
            SVProgressHUD.setDefaultMaskType(.clear)
            let vc = WBOAuthViewController()
            //设置跳转界面，一般与navigationController连用
            let nav = UINavigationController(rootViewController: vc)
            self.present(nav, animated: true, completion: nil)
        }
    }
    fileprivate lazy var composeButton:UIButton = UIButton.cz_imageButton("tabbar_compose_icon_add", backgroundImageName: "tabbar_compose_button")
    //@objc 通过OC的方式让私有方法可以得到按钮事件的访问
    //如果播放视频，通常是通过modal（模态）来实现的
    @objc fileprivate func composeButtonEvent(){
        print("按钮事件")
        let vc = UIViewController()
        vc.view.backgroundColor = UIColor.cz_random()
        let nav = UINavigationController(rootViewController: vc)
        present(nav, animated: true, completion: nil)
    }
    //portrait:肖像：竖屏
    //landscape:风景：横屏
    //在主控制器中定义之后他的子控制器也会统一被设置成为竖屏
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return .portrait
    }
    deinit {
        //销毁定时器
        timer?.invalidate()
        //注销通知
        NotificationCenter.default.removeObserver(self)
    }
}
//设置是否显示微博新特性界面
extension WBMainViewController {
    func isShowNewFeature() {
        //1.判断用户登录状态
        if !WBNetWorkManager.shared.userLogin {
            return
        }
        //2.判断版本是否更新
        //3.如果更新则显示新特性界面，如果没有则显示欢迎界面
        let loginView = isVersionUpdate ? WBNewFeatureView.newFeatureView():WBWelcomeView.welcomeView()
        //loginView.frame = view.bounds
        view.addSubview(loginView)
    }
    //extension中可以存在计算型属性,相当于一个构造函数负责分配空间。
    fileprivate var isVersionUpdate:Bool {
        //1.取出当前版本号
        //print(Bundle.main.infoDictionary)
        let currentVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? ""
        //2.取出沙盒(Document)中保存的版本号
        //拼接版本保存路径
        let path:String = ("version" as NSString).cz_appendDocumentDir()
        let sanBoxVersion = try? String(contentsOfFile: path)
        //3.将当前版本保存到沙盒中
        try? currentVersion.write(toFile: path, atomically: true, encoding: .utf8)
        //4.将当前版本与沙盒版本比较如果一致则为欢迎界面不一致说明有更新为新特性界面
        return currentVersion == sanBoxVersion
    }
}
extension WBMainViewController:UITabBarControllerDelegate{
    
    /// 设置微博切换tabbarItem事件
    ///
    /// - Parameters:
    ///   - tabBarController: tabBarController
    ///   - viewController: 目标控制器
    /// - Returns: 返回是否切换到目标控制器
    func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
        //设置即将要切换到的控制器中
        print("即将切换到\(viewController)")
        //获取目标控制器的序号
        let idx = (childViewControllers as NSArray).index(of: viewController)
        //判断是否切换和点击的控制器是首页控制器
        if selectedIndex == 0 && idx == selectedIndex{
            print("切换到首页")
            //将表格滚动到顶部
            //1>获取当前控制器
            let nav = childViewControllers[0] as! UINavigationController
            //获取栈底控制器
            let vc = nav.childViewControllers[0] as! WBHomeViewController
            //设置滚动到顶部
            vc.tv?.setContentOffset(CGPoint(x:0,y:-64) , animated: true)
            //延迟加载数据保证滚动到顶部可以同时刷新数据
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+1, execute: { 
                //刷新数据
                vc.loadData()
            })
        }
        //判断将要切换到的控制器是否是UIViewController如果是则不切换
        return !viewController.isMember(of: UIViewController.self)
    }
}
// MARK: - 封装定时器相关方法
extension WBMainViewController{
    //初始化定时器
    func setUpTimer() {
        timer = Timer.scheduledTimer(timeInterval: 60, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true)
    }
    func updateTimer() {
        if !WBNetWorkManager.shared.userLogin{
            //判断用户是否登录
            return
        }
        WBNetWorkManager.shared.unReadCount { (Count) in
            print("接收到\(Count)条新微博")
            //设置tabbaritems的badgeValue的值
            self.tabBar.items?[0].badgeValue = Count>0 ? "\(Count)":nil
            //设置app图标的badgeNumber值,ios7.0以后图标显示通知需要用户授权
            UIApplication.shared.applicationIconBadgeNumber = Count
        }
    }
}
//extension 里面不能定义属性
extension WBMainViewController{
    // 设置子控制器 fileprivate对应以前的private，现在的private是真正的私有，离开了这个类或者结构体的作用域外面无法调用
     fileprivate func getChildControllers(){
        //获取沙盒地址
        let docPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        let dataPath = (docPath as NSString).appendingPathComponent("test.json")
        print(dataPath)
        //获取沙盒数据
        var data = NSData(contentsOfFile: dataPath)
        //判断沙盒里面是否有数据
        if data == nil {
            //根据bundle方法获取url路径
             let jsonClass = Bundle.main.path(forResource: "MainData.json", ofType: nil)
            //根据url路径获取json文件里面的内容
             data = NSData(contentsOfFile: jsonClass!)
        }
        //反序列化获取json里面的数据内容
        guard let arrMs = try! JSONSerialization.jsonObject(with: data! as Data, options: []) as? [Dictionary<String, Any>] else {
            return
        }
        //print(arrMs)
        var controllers = [UIViewController]()
        for item in arrMs {
            controllers.append(setUpChildControllers(dict: item))
        }
        viewControllers = controllers
        (arrMs as NSArray).write(toFile: "/Users/renzicong/工作/swift第二天/DemoInfo.plist", atomically: true)
    }
    //添加一个撰写按钮。
    
    fileprivate func setUpComposeButton(){
        tabBar.addSubview(composeButton)
        let len = tabBar.bounds.width
        let count = CGFloat((tabBar.items?.count)!)
        let w = len/count
        //print("w=\(w),count=\(count),len=\(len)")
        //insetBy调整按钮位置方法dx为正表示向内收缩，可以让tabbarbutton展现出来盖住容错点
        composeButton.frame = tabBar.bounds.insetBy(dx: w*2, dy: 0)
        //调用按钮响应事件
        composeButton.addTarget(self, action: #selector(composeButtonEvent), for: .touchUpInside)
    }
    /// 运用字典创建一个子控制器
    ///
    /// - Parameter dict: 字典信息
    /// - Returns: 子控制器
    fileprivate func setUpChildControllers(dict:[String:Any])->UIViewController{
        //1.运用反射机制获取类
        //2.将className转换成class
        guard let claName = dict["claName"] as? String,
            let title = dict["title"] as? String,
            let imageName = dict["imageName"] as? String,
            let cla = NSClassFromString(Bundle.main.nameSpace+"." + claName) as? WBBaseViewController.Type,
            let informList = dict["informList"] as? [String:String]
            else {
                return UIViewController()
        }
        //创建视图控制器
        let vc = cla.init()
        //设置tabbar按钮文字的颜色和大小
        vc.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName:UIColor.orange], for: .highlighted)
        vc.tabBarItem.setTitleTextAttributes([NSFontAttributeName:UIFont.systemFont(ofSize: 12
            )], for: .normal)
        vc.tabBarItem.image = UIImage(named: "tabbar_"+imageName)
        vc.tabBarItem.selectedImage = UIImage(named: "tabbar_"+imageName + "_selected")?.withRenderingMode(.alwaysOriginal)
        vc.title = title
        vc.informList = informList
        //初始化nav同样会调用push方法，将vc压入栈中，nav就是通过压栈的方式来管理控制器的
        let nav = WBNavigationController(rootViewController: vc)
        return nav
    }
}
